package com.lagou.edu.controller;

import com.lagou.edu.dao.ResumeDao;
import com.lagou.edu.pojo.Resume;
import com.lagou.edu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

@Controller
public class DeomController {

    @Autowired
    private ResumeDao resumeDao;

    @RequestMapping("all")
    @ResponseBody
    public List<Resume> query(){
        List<Resume> all = resumeDao.findAll();
        return all;
    }
    @RequestMapping("login")
    public  String  loginPage(User user, Model model , HttpSession session){
        return "index";
    }
    @RequestMapping("logindo")
    public  String  login(User user, Model model , HttpSession session){
        if("admin".equals(user.getUsername())&&"admin".equals(user.getPassword())){
            session.setAttribute("user",user);
            return "redirect:main";
        }else{
            model.addAttribute("msg","登录失败，密码或账号错误");
        }
        return "index";
    }

    @RequestMapping("main")
    public  String  main(Model model){
        List<Resume> all = resumeDao.findAll();
        model.addAttribute("resumes",all);
        return "main";
    }

    @RequestMapping("delete")
    public String delete(String id){
        resumeDao.deleteById(Long.parseLong(id));
        return "redirect:main";
    }
    @RequestMapping("editpage")
    public String edit(String id,Model model){
        if(!StringUtils.isEmpty(id)){
            Optional<Resume> resum = resumeDao.findById(Long.parseLong(id));
            Resume resume = resum.get();
            model.addAttribute("resume",resume);
        }
        return "add";
    }
    @RequestMapping("/edit")
    public String edit(Resume resume){
        resumeDao.save(resume);
        return "redirect:main";
    }
}
